<template>
  <div class="calendar">
    <!-- 查询表单 -->
    <filter-form
      planType="day"
      :onSubmit="handleSearch"
      :onClear="handleClear"
      :onExport="handleExport"
    />
    <el-calendar v-model="currentDay" v-loading="loading">
      <template slot="dateCell" slot-scope="{ date, data }">
        <div
          ref="dataCell"
          slot="reference"
          class="dateCell"
          @click.stop="
            handleClickCell({
              date: data.day,
              content: '',
              username,
              user: id,
              type: true,
            })
          "
        >
          <!-- <span v-if="data.type !== 'current-month'"></span> -->
          <span v-if="isToday(data.day)">今</span>
          <span v-else :class="data.isSelected ? 'is-selected' : ''">
            {{ data.day.split("-")[2] }}
          </span>
          <ul v-if="calendarData[data.day]" class="recordList">
            <li
              v-for="(record, index) in calendarData[data.day].slice(0, 3)"
              :key="index"
              :style="{ background: TYPE_COLOR[record.classify_name]}"
              style="display:flex;"
              @click.stop="
                handleClickCell({
                  date: data.day,
                  ...record,
                })
              "
            >
              <i v-if="record.is_done" class="el-icon-check"></i>
              <!-- <img v-if="record.is_done" :src="require('@/assets/complete.png')"/> -->
              <span :style="{marginLeft:record.is_done ? '5px' : '0'}">{{ record.username + "：" + record.content }}</span>
            </li>
            <el-popover placement="right-start" width="200" trigger="hover" popper-class="popoverClass">
              <li
                slot="reference"
                v-if="calendarData[data.day].length > 3"
                @click.stop="dialogVisible = false"
              >
                {{ calendarData[data.day].length - 3 }} +
              </li>
              <ul v-if="calendarData[data.day]" class="recordList">
                <li
                  v-for="(record, index) in calendarData[data.day]"
                  :key="index"
                  :style="{ background: TYPE_COLOR[record.classify_name] }"
                  style="display:flex;"
                  @click.stop="
                    handleClickCell({
                      date: data.day,
                      ...record,
                    })
                  "
                >
                <i v-if="record.is_done" class="el-icon-check"></i>
                 <!-- <img v-if="record.is_done" :src="require('@/assets/complete.png')"/> -->
                 <span :style="{marginLeft:record.is_done ? '5px' : '0'}">{{ record.username + "：" + record.content }}</span>
                </li>
              </ul>
            </el-popover>
          </ul>
          <!-- 如果是星期天，则显示日报按钮 -->

          <div
            v-if="isSunDay(data.day)"
            class="weekly-report"
            @click.stop="handleWriteWeeklyReport(data.day)"
          >
            <el-tooltip content="填写周报" placement="top">
              <i class="el-icon-edit"></i>
            </el-tooltip>
          </div>
        </div>
      </template>
    </el-calendar>
    <el-dialog
      title="编辑内容"
      :visible.sync="dialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      :width="device === 'mobile' ? '90%' : '30%'"
      class="day-report"
    >
      <edit-plann-form
        :recordData="selectedRecord"
        :weekRecords="selectedWeekRecords"
        :dropDownList="dropDownList"
        :onSubmit="handleSave"
        :onDelete="handleDelete"
        :onCancel="() => (dialogVisible = false)"
      />
    </el-dialog>
    <!-- 创建年报 -->
    <el-dialog
      :title="`编辑年报`"
      :visible.sync="dialogYearlyReportVisible"
      :close-on-click-modal="false"
      :width="(device === 'mobile' || planType === '年') ? '96%' : '70%'"
      class="week-report-dialog"
    >
      <year-report-form
        :planType="planType"
        :weekRecords="selectedWeekRecords"
        :date="selectedDate"
        :onClose="() => (dialogYearlyReportVisible = false)"
      />
    </el-dialog>
    <!-- 创建周、月报 -->
    <el-dialog
      :title="`编辑${planType}报`"
      :visible.sync="dialogWeeklyReportVisible"
      :close-on-click-modal="false"
      :width="(device === 'mobile' || planType === '月') ? '96%' : '70%'"
      class="week-report-dialog"
    >
      <week-month-report-form
        :planType="planType"
        :weekRecords="selectedWeekRecords"
        :date="selectedDate"
        :onClose="() => (dialogWeeklyReportVisible = false)"
      />
    </el-dialog>
    <!-- 日历导出日期筛选 -->
    <date-select-form-modal
      modalTitle="选择日期"
      :dialogVisible="dialogDateFormVisible"
      :onClose="() => { dialogDateFormVisible = false }"
      :onSubmit="handleFetchExport"
    />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import _ from 'lodash'
import { parseTime, groupBy, rowToColumnOfJsonData, downloadBinaryFile } from "@/utils/index.js";
import {
  getCalendarPlan,
  createCalendarPlan,
  updateCalendarPlan,
  deleteCalendarPlan
} from "@/api/plann.js";
import { getTaskClassify } from "@/api/work.js";


export default {
  computed: {
    ...mapGetters(["name", "id"]),
    device() {
      return this.$store.state.app.device;
    },
    username() {
      return this.name && this.name.split("(")[0];
    },
  },
  components: {
    EditPlannForm: () => import("./EditPlannForm.vue"),
    FilterForm: () => import("../components/FilterForm.vue"),
    WeekMonthReportForm: () => import("../components/WeekMonthReportForm.vue"),
    YearReportForm: () => import("../components/YearReportForm.vue"),
    DateSelectFormModal: () => import('../components/DateSelectFormModal.vue')
  },
  data() {
    return {
      WEEK_DAY: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
      TYPE_COLOR: { 会议: "#67c23a", 调研: "#e6a23c", 出差: "#4f9fee", 办公: "mediumaquamarine", 考察: "#f67070"},
      loading: false,
      currentDay: new Date(),
      calendarRange: [],
      dropDownList: [],
      content: "",
      planType: '周',
      calendarData: {},
      dialogVisible: false,
      dialogWeeklyReportVisible: false,
      dialogYearlyReportVisible: false,
      dialogDateFormVisible: false,
      selectedRecord: null,
      selectedDate: null,
      selectedWeekRecords: [],
      queryParam: {},
    };
  },
  created() {
    this.$nextTick(() => {
      // 点击前一个月
      let prevBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(1)"
      );
      prevBtn.addEventListener("click", this.fetchCalendarPlanList);

      //点击下一个月
      let nextBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(3)"
      );
      nextBtn.addEventListener("click", this.fetchCalendarPlanList);

      //点击今天
      let todayBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(2)"
      );
      todayBtn.addEventListener("click", this.fetchCalendarPlanList);
      // 手动新增caleder日历后添加写月报按钮
      this.createCalendarHeaderBtn();
    });
  },
  mounted() {
    this.fetchCalendarPlanList();
    this.fetchClassifyList() // 请求classify类型列表
  },
  methods: {
    parseTime,
    // 创建按钮DOM
    createCalendarHeaderBtn() {
      const monthBtn = document.createElement("span");
      monthBtn.innerHTML = "写月报";
      monthBtn.setAttribute("class", "header-btn header-btn__month");
      monthBtn.addEventListener("click", () => {
        this.planType = '月'
        this.dialogWeeklyReportVisible = true
        });
      const yearBtn = document.createElement("span");
      yearBtn.innerHTML = "写年报";
      yearBtn.setAttribute("class", "header-btn header-btn__year");
      yearBtn.addEventListener("click", () => {
        this.planType = '年'
        this.dialogYearlyReportVisible = true
        });
      const calendarHeader = document.querySelector(".el-calendar__title");
      calendarHeader.appendChild(monthBtn);
      calendarHeader.appendChild(yearBtn);
    },
    // 点击查询
    handleSearch(param) {
      const { user, content, userType, type, group } = param;
      const _param = {
        content,
        type,
      };
      // 当user为 u{id} 将u去除
      const _user = typeof user === "string" ? user.slice(1) : user;
      if (userType === "user") {
        _param.user = _user;
      } else {
        _param.department = _user;
      }
      if(group && group.length) {
        _param.group = group.join(',')
      }
      this.fetchCalendarPlanList(_param);
    },
    // 重置查询表单
    handleClear() {
      this.queryParam = {}
      this.fetchCalendarPlanList();
    },
    // 导出
    handleExport(date) {
      const { department, date_start, date_end, type } = this.queryParam
      
      // 空数据导出判断
      if(_.isEmpty(this.calendarData)) {
        this.$message.warning('暂无数据可以导出')
        return
      }
      // 选择特殊部门
      // if(department == 10000) {
      //   this.dialogDateFormVisible = true;
      // } else {
      // 普通打印 前端excel导出
      const { tableHeader, tableData } = rowToColumnOfJsonData(
        this.calendarData
      );
      import("@/vendor/Export2Excel").then((excel) => {
        excel.export_json_to_excel({
          header: tableHeader,
          data: tableData,
          filename: `${date_start}至${date_end}日程`,
        });
      });
    },
    // 特殊部门请求后端 导出word文件
    async handleFetchExport(date) {
      this.dialogDateFormVisible = false
      const { protocol, host } = window.location
      window.open(`${protocol}//${host}/api/Work/schedule_save_docx/?type=日报&date=${parseTime(date, '{y}-{m}-{d}')}`)
    },
    // 判断日历是否是今天
    isToday(date) {
      // this.calendarRange.push(date)
      return parseTime(new Date(), "{y}-{m}-{d}") === date;
    },
    // 判断日历是否是星期天
    isSunDay(date) {
      const week = new Date(date).getDay();
      return !week;
    },
    /**
     * 点击日历单元格，保存点击日期所在周的所有日期
     */
    handleClickCell(value) {
      const { date } = value;
      const weekDays = this.getWeekDays(date);
      const weekRecords = this.getWeekRecords(weekDays);
      this.selectedWeekRecords = weekRecords;
      this.dialogVisible = true;
      let newValue = value
        if(value.take_time_unit == '' || value.take_time_unit == null || value.take_time_unit == undefined){
          newValue = {...value,take_time_unit:'min'}
        }
      this.selectedRecord = newValue;
    },
    handleWriteWeeklyReport(date) {
      const weekDays = this.getWeekDays(date);
      const weekRecords = this.getWeekRecords(weekDays);
      this.selectedWeekRecords = weekRecords;
      this.selectedDate = date;
      this.planType = '周'
      this.dialogWeeklyReportVisible = true;
    },
    /**
     * 点击新增、修改报告确定按钮
     */
    handleSave: _.debounce(async function(record) {
      const { id } = record;
      let result = null;
      
      // id存在，进行更新操作
      if (id) {
        const { data } = await updateCalendarPlan(id, record);
        result = data;
      } else {
        const { data } = await createCalendarPlan(record);
        result = data;
      }
      if (result && result.id) {
        this.$message.success("保存成功");
        this.dialogVisible = false;
        this.fetchCalendarPlanList();
      }
    }, 500
    ),
    /**
     * 点击删除报告按钮
     */
    async handleDelete(id) {
      await deleteCalendarPlan(id);
      this.fetchCalendarPlanList();
      this.dialogVisible = false;
    },
    /**
     * 按照date进行分组
     */
    groupListByDate(list) {
      if (!list.length) return {};
      return groupBy(list, "date");
    },
    /**
     * 输入指定日期，返回日期所在周的所有日期数组
     */
    getWeekDays(input_day = "") {
      if (!input_day) return [];
      let oneDayTime = 1000 * 60 * 60 * 24;
      let today = new Date(input_day);
      // 若那一天是周末时，则强制赋值为7
      let todayDay = today.getDay() || 7;
      let startDate = new Date(today.getTime() - oneDayTime * (todayDay - 1));
      let dateList = new Array();
      for (let i = 0; i < 7; i++) {
        let temp = new Date(startDate.getTime() + i * oneDayTime);
        let year = temp.getFullYear();
        let month = temp.getMonth() + 1;
        let day = temp.getDate();
        const _month = month < 10 ? "0" + month : month;
        const _day = day < 10 ? "0" + day : day;
        dateList[i] = `${year}-${_month}-${_day}`;
      }
      return dateList;
    },
    /**
     * 传入一周所有日期，返回指定日期范围内数据
     */
    getWeekRecords(weekDays) {
      if (!weekDays.length) return [];
      const _calendarData = this.calendarData;
      const result = [];
      Object.keys(_calendarData).forEach((key) => {
        if (weekDays.includes(key)) {
          result.push(..._calendarData[key]);
        }
      });
      return result;
    },
    /**
     * 获取日历开始和结束日期
     */
    getStartAndEndDate() {
      const date = parseTime(this.currentDay, "{y}-{m}-{d}");
      this.selectedDate = date;
      const [year, month, day] = date.split("-");
      const base = `${year}-${month}`;
      // 日历开始日期
      const [start] = this.getWeekDays(base + "-01");
      // 日历结束日期
      const lastNextNode = Array.from(
        document.querySelectorAll(".next")
      ).reverse()[0];
      const lastDay = lastNextNode && lastNextNode.outerText;

      let nextMonth = 1
      let _year = year
      // 如果是12月 则进入下一年
      if( month > 11) {
        nextMonth = "01"
        _year = Number(year) + 1
      } else {
        nextMonth = parseInt(month) + 1
      }
      const end = `${_year}-${nextMonth}-${lastDay}`;

      return {
        date_start: parseTime(new Date(start), "{y}-{m}-{d}"),
        date_end: parseTime(new Date(end), "{y}-{m}-{d}"),
      };
    },
    /**
     * 请求日历报告记录
     */
    async fetchCalendarPlanList(filter) {
      this.loading = true;
      this.calendarData = {}
      const { date_start, date_end } = this.getStartAndEndDate();
      const param = {
        date_start,
        date_end,
      };
      this.queryParam = { ...this.queryParam, ...param, ...filter };
      try {
        const { data } = await getCalendarPlan(this.queryParam);
        const dateList = this.groupListByDate(data);

        this.calendarData = dateList;
        this.loading = false;
      } catch (error) {
        this.loading = false;
      }
    },
    // 请求classify类型列表
    async fetchClassifyList() {
      const {
        data: { results }
      } = await getTaskClassify({ type: "schedule" });
      this.dropDownList = results
    },
  },
};
</script>
<style lang="scss" scope>
.calendar {
  .dateCell {
    height: 100%;
    position: relative;
    padding: 8px;

    .weekly-report {
      height: 100%;
      display: flex;
      align-items: center;
      position: absolute;
      top: 0;
      right: -37px;
      > i {
        color: #fff;
        background: sandybrown;
        border-radius: 50%;
        font-size: 16px;
        padding: 3px;
      }
    }
  }
  .header-btn {
    padding: 2px 4px;
    margin-right: 10px;
    border: 1px solid currentColor;
    font-size: 12px;
    cursor: pointer;
    &__month {
      color: #1989fa;
      &:hover {
        color: #fff;
        background: #1989fa;
      }
    }
    &__year{
      color: #67c23a;
      &:hover {
        color: #fff;
        background: #67c23a;
;
      }
    }
  }
  .is-selected {
    color: #1989fa;
  }
}
</style>
<style lang="scss">
.calendar {
  margin-right: 8px;
  .el-calendar__body {
    width: 98.5%;
    padding: 0 20px 10px;
    .el-calendar-day {
      padding: 0;
    }
  }
  .el-calendar-table {
    // height: calc(100vh - 150px);
    &:not(.is-range) {
      //使不是本月的日期不可点击，不会跳转到其他月份
      // td.next {
      //   pointer-events: none;
      //   border-right: none;
      //   border-bottom: none;
      // }
      // td.prev {
      //   pointer-events: none;
      //   border: none;
      //   border-top: 1px solid #ebeef5;
      //   border-bottom: 1px solid #ebeef5;
      // }
      //td{
      //    pointer-events: none;
      //}
    }
    .el-calendar-day {
      height: 128px;
    }
  }

  .day-report {
    .el-dialog__header {
      display: none;
    }
  }
  @media screen and (max-width: 500px){ 
    // 日历标题
    .el-calendar {
      .el-calendar__header {
        padding: 12px 0 12px 12px;
      }
      .el-button--mini {
        padding: 7px 10px;
      }
    }
    // 编辑周报
    .week-report-dialog {
      .person {
        margin-left: 20px;
      }
      .el-dialog__body {
        padding: 30px 0 0;
      }
      .box-card .header .extra {
        padding-right: 0;
      }
    }
  }
  .el-dialog {
    border-radius: 8px;
  }
}
.popoverClass{
  padding: 0 12px 6px;
  box-shadow: 0px 0px 20px 5px #ccc9c9;
  background-color: #FFF9E3;
  // border: 1px solid #fad551;
  max-height: 200px;
  overflow: auto;
}
.recordList {
  list-style-type: none;
  padding: 0;
  margin: 8px 0 0;

  li {
    margin-bottom: 2px;
    padding: 4px 6px;
    background: mediumaquamarine;
    color: #fff;
    font-size: 12px;
    line-height: 12px;
    border-radius: 4px;
    white-space: nowrap;
    overflow: hidden;
    -o-text-overflow: ellipsis;
    text-overflow: ellipsis;
  }
}
</style>